package com.yjz.leetcode.LRU算法;


import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 基于LinkedHashMap(这是尾插法)
 *
 * @param <K>
 * @param <V>
 */
public class LRU2<K, V> extends LinkedHashMap {
    private int capacity;

    public LRU2(int capacity) {
        this.capacity = capacity;
    }

    /**
     * It provides the implementor
     * with the opportunity to remove the eldest entry each time a new one
     * is added.  This is useful if the map represents a cache
     * @param eldest 双向链表的头节点(最老的节点)----> 尾插法实现，所以最老的是头节点
     * @return
     */
    @Override
    protected boolean removeEldestEntry(Map.Entry eldest) {
        return size() > capacity;
    }

    public static void main(String[] args) {
        LRU2<String,String> lru=new LRU2(3);
        lru.put("name","张三");
        lru.put("age","15");
        lru.put("sex","男");
        System.out.println("到达极限容量的缓存"+lru);
        lru.put("weight","150斤");
        System.out.println("清除最老的缓存"+lru);
        lru.put("height","150cm");
        System.out.println("清除最老的缓存"+lru);
    }
}
